package com.mall.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mall.exception.MyException;
import com.mall.model.Commodity;
import com.mall.model.Seckill;
import com.mall.model.User;
import com.mall.service.SeckillService;
import com.mall.util.MyUtil;
import com.mall.util.RedisUtil;
import com.mall.util.SeckillThread;
import com.mall.util.SerializeUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Controller
@RequestMapping("/SeckillController")
public class SeckillController extends MyUtil {
	public static Map<Integer, Integer> commstart = new HashMap<Integer, Integer>();
	public static Map<Integer, Integer> nummap = new HashMap<Integer, Integer>();
	public static String path;
	@Autowired
	private SeckillService seckillService;

	/**
	 * 创建秒杀
	 *
	 * @dagewang 2017年9月29日
	 */
	@RequestMapping("/create")
	public @ResponseBody Integer create(Double price, String sdate, String edate, Integer id, Integer num,
			HttpServletRequest hsr) throws Exception {
		if (!this.isNull(sdate, edate, id, num)) {
			path = hsr.getServletContext().getRealPath("/seckill/");
			Integer result = seckillService.save(price, sdate, edate, id, num, path);
			if (result != null) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				Date date = sdf.parse(sdate);
				Date date2 = sdf.parse(edate);
				SeckillThread.setTimeAndId(date, result, num, date2);
				return 1;
			}
		}
		return 0;
	}

	/**
	 * 秒杀
	 *
	 * @dagewang 2017年9月29日
	 */
	@RequestMapping("seckill")
	public String seckill(HttpSession session, Integer id) throws Exception {
		if (commstart.get(id) == null || commstart.get(id) == 0) {
			throw new MyException("商品已售罄!");
		} else {
			int num = nummap.get(id);
			if (num <= 0) {
				throw new MyException("商品已售罄!");
			}
			synchronized (this) {
				int snum = nummap.get(id);
				if (snum > 0) {
					Object attribute = session.getAttribute("user");
					if (attribute != null) {
						nummap.put(id, snum - 1);
						User u = (User) attribute;
						Integer result = seckillService.createOrder(u.getId(), id, snum);
						if (result == null || result == 0) {
							nummap.put(id, snum + 1);
							throw new MyException("购买失败!");
						}
						if (snum == 1) {
							nummap.remove(id);
							commstart.remove(id);
						}
						return "redirect:/CartController/listCartByUser.action";
					} else {
						throw new MyException("请您登陆后再购买!");
					}
				}

			}
		}
		return "error";
	}

	/**
	 * 秒杀商品集合
	 * 
	 * @dagewang 2017年9月29日
	 */
	@RequestMapping("/list")
	public String list(Model model, Integer page, HttpSession session) {
		if (page == null || page.equals("")) {
			page = 0;
		}
		List<Seckill> slist = seckillService.list(page);
		if (slist.size() != 0) {
			model.addAttribute("slist", slist);
		}
		model.addAttribute("page", page);
		return "seckill_mode";

	}

	/**
	 * 后台管理获取秒杀商品集合
	 *
	 * @dagewang 2017年10月9日
	 */
	@RequestMapping("/sysList")
	public String sysList(Model model, Integer page, HttpSession session) {
		Object attribute = session.getAttribute("adminuser");
		if (attribute == null) {
			return "adminLogin";
		}
		if (page == null || page.equals("")) {
			page = 0;
		}
		List<Seckill> slist = seckillService.syslist(page);
		if (slist.size() != 0) {
			model.addAttribute("slist", slist);
		}
		model.addAttribute("page", page);
		return "sysUpdateKill";

	}

	/**
	 * 更新秒杀商品信息
	 *
	 * @dagewang 2017年10月9日
	 */
	@RequestMapping("/update")
	public @ResponseBody Integer update(Seckill seckill) {
		if (this.isNull(seckill.getId(), seckill.getCountnum(), seckill.getPrice(), seckill.getState())) {
			return 0;
		}
		return seckillService.updateData(seckill);
	}

	@RequestMapping("/redisToView")
	public String redisToView(Model model) {
		model.addAttribute("page", 0);
		JedisPool jedis = RedisUtil.getJedis();
		Jedis r = jedis.getResource();
		byte[] bs = r.get("seckills".getBytes());
		Seckill[] unserialize=null;
		try {
			unserialize = (Seckill[]) SerializeUtil.unserialize(bs);
		} catch (Exception e) {
			e.printStackTrace();
			}
		RedisUtil.close(jedis, r);
		model.addAttribute("slist", unserialize);
		return "seckill_mode";
	}

	public void setSeckillService(SeckillService seckillService) {
		this.seckillService = seckillService;
	}

	public SeckillService getSeckillService() {
		return seckillService;
	}

}
